jQuery(function($){
   
   $('#in').html("<a class='print-coupon' target='_blank' href='"+ $('#wp-admin-bar-view a.ab-item').attr('href')+"'>Print</a>");
   $('#in').parents('#postbox-container-2').addClass("top_right");
   $('#in').parents('#postbox-container-2').prev('#postbox-container-1').css('margin-top','47px');
   $('#in').parents('.inside').prev('h3.hndle').hide();
   $('#test_bug').css({"display":"none"});
    
  
});
/* check in array */
Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i]+"" === obj+"") {
            return true;
        }
    }
    return false;
}

/* format a price in JavaScript */
Number.prototype.formatMoney = function(c, d, t){
var n = this, 
    c = isNaN(c = Math.abs(c)) ? 2 : c, 
    d = d == undefined ? "." : d, 
    t = t == undefined ? "," : t, 
    s = n < 0 ? "-" : "", 
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
    j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };
 
 function makeid($num)
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < $num; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}
 
/* -------------Class Customer-------------------------- */
function Custumer(obj){
    
	/* property */
	for(var key in obj){
		this[key] = obj[key];
	}
	

	/**
	 * method show customer info 
	 */
	this.get_html = function(labels){
		var str_aray = new Array();
		for (var key in labels){
			this[key] = this[key];
			var html = "<li>";
			html 	+= "	<label><strong>"+labels[key]+" </strong></label><strong>:</strong>";
			if(key=='message'){
				html 	+= "	<textarea class='field-customer' name='"+key+"'>"+this[key]+"</textarea>";
			}else{
				html 	+= "	<input class='field-customer' name='"+key+"' value='"+this[key]+"' />";
			}
			html 	+= "</li>";
			str_aray.push( html );
		}
		return "<form class='cutomer-info'><ul>"+ str_aray.join("")+ "</ul><div class='cb'></div></form>";
	}

	/**
	 * method toString json
	 */
	 this.toString = function(){
		return JSON.stringify(this);
	 }
		
	/**
	 * method appendTo
	 */
	 this.renderTo = function(element,labels){
		element.find('.cutomer-info').remove();
		/* render table */
		var table = this.get_html(labels);
		element.append(table);
		return this;
	}
	
	/** 
	 * update
	 */
	 this.set = function(name, value){
		this[name] = value;
	 }
}
/* -------------End Class Customer-------------------------- */

/**
 * Method create row table 
 */

jQuery.fn.renderContent = function($inputField, $index, $datas){;
    var $=jQuery;    
    var rows = new Array();
    for(var key in $datas) {
        var el = "<td><input type='text' value='"+$datas[key]+"' class='field "+key+"' rel='"+key+"' /></td>";
        rows.push(el);
    }
    rows.push("<td style='text-align:center;'><a rel='"+$index+"' href='#' class='remove'>x</a></td>");
    
    var html = rows.join();
 
    if($inputField != undefined){
        var data_json = $.parseJSON($inputField.val());
        if(jQuery.isEmptyObject(data_json)){
            data_json = new Array;
        }
        
        data_json[$index] = $datas;
        $inputField.val(JSON.stringify(data_json));
    }
    return this.append(html);
}


/*================================Product Customs Field============================*/
jQuery.fn.JamProduct = function(){
	var $=jQuery;
	return this.each(function(){
		var inputData = $(this).find("[name=\'"+ $(this).attr("id")+"\']");
        
        /* hide inputData */
        inputData.hide();
        
        /* Add style */
        inputData.parent().addClass('fields');
		
		/* khoi tao table */
        table_html  = "<thead>";
        table_html  +="<tr>";
        table_html  +="     <th rowspan='2'>Mã Calucky</th>";
        table_html  +="     <th colspan='3'>Size(cm)</th>";
        table_html  +="     <th rowspan='2'>Giá</th>";
        table_html  +="     <th rowspan='2'>Khuyến mãi</th>";      
        table_html  +="     <th rowspan='2'>Xóa</th>";
        table_html  +="</tr>";
        table_html  +="<tr>";
        table_html  +="     <th style='width: 80px;'>Rộng</th>";
        table_html  +="     <th style='width: 80px;'>Cao</th>";
        table_html  +="     <th style='width: 80px;'>Dài</th>";
        table_html  +="</tr>";
        table_html  +="</thead>";
        table_html  +="<tbody></tbody>";
		var table = $("<table width='100%' border='1' class='jam-product' />");
        table.html(table_html);
		table.appendTo(inputData.parent());
		
		/* Ve cac file da luu trong input vao table */        
        var data_json = $.parseJSON(inputData.val());
        if(jQuery.isEmptyObject(data_json)){
                data_json = new Array;
        }        
        $(data_json).each(function($index,$datas){
            var row = $("<tr />").appendTo(table.children("tbody"));
            row.renderContent(inputData,$index,$datas);
        });
		
		/* Click vao button them field */        
        var btn_add = $("<a class='button' style='float:right;margin-top:10px;' />")
        .html("+Thêm mới").click(function(){            
			/* chi muc dong */
			var index = (table.find('tr').length-2);
			/* tao dong */
			var row = $("<tr />").appendTo(table.children("tbody"));
			var datas = {code:'',width:'',height:'',length:'',price:'',sale:''}; 
			row.renderContent(inputData,index,datas);
                      
        }).appendTo(inputData.parent());
		
		/* Remove field */
        $(".remove").live("click",function(){            
			var index = $(this).attr("rel");
			var data_json = $.parseJSON(inputData.val());
			if(jQuery.isEmptyObject(data_json)){
				data_json = new Array;
			}
			data_json.splice(index, 1);
			inputData.val(JSON.stringify(data_json));            
			$(this).parent("td").parent("tr").css("background","#FF8080");
			$(this).parent("td").parent("tr").fadeOut("slow",function(){
				$(this).remove();
			});
			return false;
        });
        
        /* input change */
        $(this).find(".field").live("change",function(){
			var trow = $(this).parent("td").parent("tr");
			var index = trow.find("a.remove").attr("rel");
			var data_json = $.parseJSON(inputData.val());
			if(jQuery.isEmptyObject(data_json)){
					data_json = new Array;
			}

			var datas = new Object();
			trow.find('.field').each(function(){
				var key = $(this).attr('rel');
				var value = $(this).val();
				datas[key] = value;
			});     
			data_json[index] = datas;
			inputData.val(JSON.stringify(data_json));            
        });
	});
}

jQuery.fn.jamOrderDetail = function(){
	var $=jQuery;
	return this.each(function(){
		$(this).hide();
		var data_json = $.parseJSON(this.value);
		if(jQuery.isEmptyObject(data_json)){
			return this;
		}
		/* Duyet qua tung loai */
		var order_detail = $("<div id='order-list' />").appendTo($(this).parent());
		var types = {'checkout':'Danh sách sản phẩm'};
		var thead_labels = {
			image: 'Hình',
			sizename: 'Size',
			colorname: 'Màu',
			qty: 'Số lượng',
			price: 'Giá (vnđ)',
			sale: 'Khuyến mãi (vnđ)'
		};
		
		$.each(types,function(type,type_label){
			if(data_json[type] != undefined) {
				/* create table */
				var table = $("<table border='1' class='jam-product wp-list-table widefat' />");
				/* create thead */
				var thead = "<thead><tr>";
				for(var tkey in thead_labels){
					thead+="<th class='order-"+tkey+"'>" + thead_labels[tkey] + "</th>";
				};
				thead += "</tr></thead>";
				table.append(thead).appendTo(order_detail);
				/* create tbody */
				var tbody = $("<tbody />").appendTo(table);
				/* create tbody->trow */
				data_json[type].forEach(function(items){
					var trow = $("<tr/>").appendTo(tbody);
					for(var tkey in thead_labels){
						var content = "";
						if(tkey=='colorname'){
							if(items['colorimg']!=null){
								content = "<a title='"+items['colorname']+"'><img src='"+items['colorimg']+"' style='width: 30px;' /></a>";
							}else if(items['colorhex']!=""){
								content = "<a title='"+items['colorname']+"'><span style='background:"+items['colorhex']+"; display:block; width: 30px; height: 30px; margin: 0 auto;'></span></a>";
							}else{
								content = items['colorname'];
							}
						}else if((tkey=='price' || tkey=='sale') && items[tkey]!=''){
							var money = parseInt(items[tkey]);
							content = money.formatMoney(0,',','.');
						}else if(tkey=='image'){
							content = "<a title='"+items['name']+"' href='"+items['url']+"'><img src='"+items['image']+"' style='width:80px;' /></a>";
						}else{
							content = items[tkey];
						}
						trow.append("<td class='center'>"+content+"</td>");
					}
				});
			}
		});
		
		var total_price = parseInt(data_json['order_price']);
		var payment_method = data_json['order_payment'];
		var order_date = data_json['order_date']
		var detail 	= "<div class='detail'>";
		detail		+="		<ul>";
		detail		+="			<li><strong><label>Giá trị đơn hàng</label>:</strong> "+total_price.formatMoney(0,',','.')+" vnđ</li>";
		detail		+="			<li><strong><label>Phương thức thanh toán</label>:</strong> "+payment_method+"</li>";
		detail		+="			<li><strong><label>Ngày tạo đơn hàng</label>:</strong> "+order_date+"</li>"	;
		detail		+=		"</ul>";	
		detail		+="</div><div class='cb'></div>";
		order_detail.append(detail);
		
	});
}

/*================================Main===============================*/
jQuery(function( $ ){


	/*Quan Ly Don Hang*********************************/
	$("#size-product").hide();
	$("#product_del").css({"display":"none"});
	/* remove option select */
	$("#_order-status li:last-child select[name='order-status']").find("option[value='0']").remove();

	/* select change order status */
	$("#order-statusdiv").hide();
	$("select[name='order-status']").change(function(){
		var value = $(this).val();
		$("ul#order-statuschecklist").find('input').attr('checked',false);
		$("ul#order-statuschecklist").find('input#in-order-status-'+value).attr('checked',true)
	});

	/* selecter change payment */
	$("#order-paymentdiv").hide();

	/* Tuy bien thong tin khach hang */
	var tag_content = $("#order-customer").find("li:last-child");
	var customer = $("#order-customer").find("textarea[name='order-customer']");
	if(customer.length>0){
		customer.hide();
		var data_json = $.parseJSON(customer.val());
		if(!jQuery.isEmptyObject(data_json)){   
			var data_json = $.parseJSON(customer.val());
			var cObj = new Custumer(data_json);
			var labels = {  
					fullname: 'Họ tên', 
					phone:'Điện thoại', 
					email: 'Email',
					local:'Tình/Thành', 
					district: 'Quận/Huyện', 
					address: 'Địa chỉ',
				};
			
			cObj.renderTo(tag_content,labels);
			
			tag_content.find(".field-customer").live('change',function(){
				cObj.set(this.name,this.value);
				customer.val(cObj.toString());
			});
			
		}
	}
	/* Tuy bien thong tin nguoi nhan hang */
	var tag_content2 = $("#_customer").find("li:last-child");
	var _customer = $("#_customer").find("textarea[name='_customer']");
	if(_customer.length>0){
		_customer.hide();
		var data_json = $.parseJSON(_customer.val());
		if(!jQuery.isEmptyObject(data_json)){   
			var data_json = $.parseJSON(_customer.val());
			var cObj = new Custumer(data_json);
			var labels = {  
					fullname: 'Họ tên', 
					phone:'Điện thoại', 
					email: 'Email',
					local:'Tỉnh/Thành', 
					district: 'Quận/Huyện', 
					address: 'Địa chỉ',
				};
			
			cObj.renderTo(tag_content2,labels);
			
			tag_content2.find(".field-customer").live('change',function(){
				cObj.set(this.name,this.value);
				_customer.val(cObj.toString());
			});
			
		}
	}
	
	/* Tuy bien chi tiet don hang */
	$("textarea[name='order-detail']").jamOrderDetail();
	
	/* phat sinh ma coupon */
	code_coupon = $("input[name='code_coupon']");
	if(code_coupon.length>0){
		var btn = $("<a class='button' href='#' />").text("General").appendTo(code_coupon.parent());
		btn.click(function(){
			var code = makeid(12);
			code_coupon.val( code.toUpperCase() );
			return false;
		});
		
		var coupon_number1 = $("input[name='coupon_number1']");
		if(coupon_number1.val()==""){
			coupon_number1.val(0);
		}
		
		var coupon_number2 = $("input[name='coupon_number2']");
		if(coupon_number2.val()==""){
			coupon_number2.val(0);
		}
		
		$("input[name='form_date'],input[name='to_date']").datepicker({
			dateFormat: 'yy-mm-dd',
			changeMonth: true,
			changeYear: true,
			yearRange: "-80:+80",
		});
		
		// Check type coupons
		$("input[name='coupon_type']").parent("li").append("<i class='desc'>Nếu không chọn mặc định giảm theo số tiền!</i>");
		$("input[name='coupon_type']").change(function(){
			$(".persymble").remove();
			if($(this).is(":checked")){
				$("input[name='coupon_value']").parent().append("<span class='persymble'>%</span>");
			}else{
				$("input[name='coupon_value']").parent().append("<span class='persymble'>VNĐ</span>");
			}
		});
		if($("input[name='coupon_type']").is(":checked")){
			$("input[name='coupon_value']").parent().append("<span class='persymble'>%</span>");
		}else{
			$("input[name='coupon_value']").parent().append("<span class='persymble'>VNĐ</span>");
		}
	}
});



